'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { SimpleSearch } from '@/components/docs/search';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  BookOpen,
  ChevronRight,
  ChevronDown,
  Clock,
  User,
  Tag,
  Menu,
  X,
} from 'lucide-react';
import { Doc, DocCategory, TableOfContent } from '@/lib/docs';

interface DocsLayoutProps {
  doc: Doc;
  categories: DocCategory[];
  relatedDocs: Doc[];
  children: React.ReactNode;
}

/**
 * 文档布局组件
 * 提供文档导航、搜索和内容展示功能
 */
export function DocsLayout({
  doc,
  categories,
  relatedDocs,
  children,
}: DocsLayoutProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set()
  );
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const pathname = usePathname();

  // 初始化展开当前文档所在的分类
  useEffect(() => {
    const currentCategory = categories.find(cat =>
      cat.docs.some(d => d.slug === doc.slug)
    );
    if (currentCategory) {
      setExpandedCategories(prev => new Set([...prev, currentCategory.slug]));
    }
  }, [doc.slug, categories]);

  /**
   * 切换分类展开状态
   */
  const toggleCategory = (categorySlug: string) => {
    setExpandedCategories(prev => {
      const newSet = new Set(prev);
      if (newSet.has(categorySlug)) {
        newSet.delete(categorySlug);
      } else {
        newSet.add(categorySlug);
      }
      return newSet;
    });
  };

  /**
   * 过滤文档
   */
  const filteredCategories = categories
    .map(category => ({
      ...category,
      docs: category.docs.filter(
        d =>
          searchQuery === '' ||
          d.meta.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          d.meta.description
            .toLowerCase()
            .includes(searchQuery.toLowerCase()) ||
          (d.meta.tags || []).some(tag =>
            tag.toLowerCase().includes(searchQuery.toLowerCase())
          )
      ),
    }))
    .filter(category => category.docs.length > 0);

  /**
   * 获取难度颜色
   */
  const getDifficultyColor = (difficulty?: string) => {
    switch (difficulty) {
      case 'beginner':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';
      case 'intermediate':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300';
      case 'advanced':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300';
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* 移动端头部 */}
      <div className="lg:hidden bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
        <div className="flex items-center justify-between">
          <h1 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
            文档
          </h1>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setSidebarOpen(!sidebarOpen)}
          >
            {sidebarOpen ? (
              <X className="h-5 w-5" />
            ) : (
              <Menu className="h-5 w-5" />
            )}
          </Button>
        </div>
      </div>

      <div className="flex">
        {/* 侧边栏 */}
        <aside
          className={cn(
            'fixed inset-y-0 left-0 z-50 w-80 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 transform transition-transform duration-200 ease-in-out lg:translate-x-0 lg:static lg:inset-0',
            sidebarOpen ? 'translate-x-0' : '-translate-x-full'
          )}
        >
          <div className="flex flex-col h-full">
            {/* 搜索框 */}
            <div className="p-4 border-b border-gray-200 dark:border-gray-700">
              <SimpleSearch
                onSearch={setSearchQuery}
                placeholder="搜索文档..."
              />
            </div>

            {/* 导航菜单 */}
            <ScrollArea className="flex-1">
              <nav className="p-4 space-y-2">
                {filteredCategories.map(category => {
                  const isExpanded = expandedCategories.has(category.slug);

                  return (
                    <div key={category.slug}>
                      <button
                        onClick={() => toggleCategory(category.slug)}
                        className="flex items-center justify-between w-full px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
                      >
                        <div className="flex items-center space-x-2">
                          <BookOpen className="h-4 w-4" />
                          <span>{category.name}</span>
                          <Badge variant="secondary" className="text-xs">
                            {category.docs.length}
                          </Badge>
                        </div>
                        {isExpanded ? (
                          <ChevronDown className="h-4 w-4" />
                        ) : (
                          <ChevronRight className="h-4 w-4" />
                        )}
                      </button>

                      {isExpanded && (
                        <div className="ml-4 mt-1 space-y-1">
                          {category.docs.map(docItem => {
                            const isActive =
                              pathname === `/docs/${docItem.slug}`;

                            return (
                              <Link
                                key={docItem.slug}
                                href={`/docs/${docItem.slug}`}
                                className={cn(
                                  'block px-3 py-2 text-sm rounded-md transition-colors',
                                  isActive
                                    ? 'bg-blue-100 text-blue-900 dark:bg-blue-900 dark:text-blue-100'
                                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-gray-100'
                                )}
                                onClick={() => setSidebarOpen(false)}
                              >
                                <div className="flex items-center justify-between">
                                  <span className="truncate">
                                    {docItem.meta.title}
                                  </span>
                                  {docItem.meta.difficulty && (
                                    <Badge
                                      variant="outline"
                                      className={cn(
                                        'text-xs ml-2',
                                        getDifficultyColor(
                                          docItem.meta.difficulty
                                        )
                                      )}
                                    >
                                      {docItem.meta.difficulty}
                                    </Badge>
                                  )}
                                </div>
                              </Link>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </nav>
            </ScrollArea>
          </div>
        </aside>

        {/* 主内容区域 */}
        <main className="flex-1 lg:ml-0">
          <div className="max-w-4xl mx-auto">
            <div className="flex">
              {/* 文档内容 */}
              <article className="flex-1 px-4 py-8 lg:px-8">
                {/* 文档头部信息 */}
                <header className="mb-8">
                  <div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400 mb-4">
                    <Link
                      href="/docs"
                      className="hover:text-gray-700 dark:hover:text-gray-300"
                    >
                      文档
                    </Link>
                    <ChevronRight className="h-4 w-4" />
                    <span>{doc.meta.category}</span>
                    <ChevronRight className="h-4 w-4" />
                    <span className="text-gray-900 dark:text-gray-100">
                      {doc.meta.title}
                    </span>
                  </div>

                  <h1 className="text-4xl font-bold text-gray-900 dark:text-gray-100 mb-4">
                    {doc.meta.title}
                  </h1>

                  <p className="text-xl text-gray-600 dark:text-gray-400 mb-6">
                    {doc.meta.description}
                  </p>

                  {/* 元数据 */}
                  <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
                    {doc.meta.author && (
                      <div className="flex items-center space-x-1">
                        <User className="h-4 w-4" />
                        <span>{doc.meta.author}</span>
                      </div>
                    )}

                    <div className="flex items-center space-x-1">
                      <Clock className="h-4 w-4" />
                      <span>{doc.readingTime.text}</span>
                    </div>

                    {doc.meta.publishedAt && (
                      <div>
                        发布于{' '}
                        {new Date(doc.meta.publishedAt).toLocaleDateString(
                          'zh-CN'
                        )}
                      </div>
                    )}

                    {doc.meta.difficulty && (
                      <Badge
                        className={getDifficultyColor(doc.meta.difficulty)}
                      >
                        {doc.meta.difficulty}
                      </Badge>
                    )}
                  </div>

                  {/* 标签 */}
                  {doc.meta.tags && doc.meta.tags.length > 0 && (
                    <div className="flex items-center space-x-2 mt-4">
                      <Tag className="h-4 w-4 text-gray-400" />
                      <div className="flex flex-wrap gap-2">
                        {doc.meta.tags.map(tag => (
                          <Badge
                            key={tag}
                            variant="secondary"
                            className="text-xs"
                          >
                            {tag}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </header>

                <Separator className="mb-8" />

                {/* MDX 内容 */}
                <div className="prose prose-gray dark:prose-invert max-w-none">
                  {children}
                </div>

                {/* 相关文档 */}
                {relatedDocs.length > 0 && (
                  <section className="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700">
                    <h2 className="text-2xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
                      相关文档
                    </h2>
                    <div className="grid gap-4 md:grid-cols-2">
                      {relatedDocs.map(relatedDoc => (
                        <Link
                          key={relatedDoc.slug}
                          href={`/docs/${relatedDoc.slug}`}
                          className="block p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-gray-300 dark:hover:border-gray-600 transition-colors"
                        >
                          <h3 className="font-medium text-gray-900 dark:text-gray-100 mb-2">
                            {relatedDoc.meta.title}
                          </h3>
                          <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                            {relatedDoc.meta.description}
                          </p>
                          <div className="flex items-center justify-between mt-3">
                            <Badge variant="outline" className="text-xs">
                              {relatedDoc.meta.category}
                            </Badge>
                            <span className="text-xs text-gray-500">
                              {relatedDoc.readingTime.text}
                            </span>
                          </div>
                        </Link>
                      ))}
                    </div>
                  </section>
                )}
              </article>

              {/* 目录 */}
              {doc.toc.length > 0 && (
                <aside className="hidden xl:block w-64 pl-8">
                  <div className="sticky top-8">
                    <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-4">
                      目录
                    </h3>
                    <TableOfContents toc={doc.toc} />
                  </div>
                </aside>
              )}
            </div>
          </div>
        </main>
      </div>

      {/* 移动端遮罩 */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}
    </div>
  );
}

/**
 * 目录组件
 */
interface TableOfContentsProps {
  toc: TableOfContent[];
}

function TableOfContents({ toc }: TableOfContentsProps) {
  const [activeId, setActiveId] = useState<string>('');

  useEffect(() => {
    const observer = new IntersectionObserver(
      entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      { rootMargin: '-100px 0px -80% 0px' }
    );

    toc.forEach(item => {
      const element = document.getElementById(item.id);
      if (element) {
        observer.observe(element);
      }
    });

    return () => observer.disconnect();
  }, [toc]);

  return (
    <nav className="space-y-1">
      {toc.map(item => (
        <a
          key={item.id}
          href={`#${item.id}`}
          className={cn(
            'block text-sm py-1 transition-colors',
            item.level === 1 && 'font-medium',
            item.level === 2 && 'ml-4',
            item.level === 3 && 'ml-8',
            item.level >= 4 && 'ml-12',
            activeId === item.id
              ? 'text-blue-600 dark:text-blue-400'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100'
          )}
        >
          {item.title}
        </a>
      ))}
    </nav>
  );
}
